var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //
    people: null,
    code: null,
    teacher_account: null,
    className: null,
    chooseStudentName: null,
    stu_name: null,
    show_studentAnswer: false,

    //页面显示切换参数
    teacher_buttonShow: true,
    student_buttonShow: false,

    //学生端相关数据
    chooseFlag: false,
    coursename: null,
    stuaccount: null,

    //学生题目相关数据
    blindBoxId: null,
    timu: null,
    studentAnswer: null,
    is_right: null,
    exam_paper_id:null,
    titleId: null,
    questionType: null,
    paperId: null,
    timu_title: null,
    stu_answer: null,
    true_answer:null,

    //组件相关参数
    modal_show_1: false,  //抽取状态窗口
    modal_show_2: false,  //抽取完成窗口
  },

  chooseStudent: function(){
    //点击触发或摇一摇触发
    let _this = this
    let data1 = {
      className: app.globalData.banji_info.courseName,
      teacherAccount: _this.data.teacher_account,
    }

    if(app.globalData.banji_info.courseStudentCount!=0){
      console.log('教师开始抽取学生')
      _this.setData({
        modal_show_1: true,
      })
      //定时关闭窗口
      setTimeout(function () {
        _this.setData({
          modal_show_1: false,
          modal_show_2: true,
        })
      }, 1500)

      app.formPost('/api/admin/blindbox/get_student',data1).then(res=>{
        console.log('本次抽取学生姓名：', res['response']['stu_name']);
        _this.setData({
          teacher_buttonShow: true,
          chooseStudentName: res['response']['stu_name']
        });
      })
    }else{
      wx.showToast({
        title: '班级人数为空！',
        icon:'none',
      })
    }
  },

  clickCancel: function(){
    this.setData({
      modal_show_1: false,
    })
  },

  Return: function(){
    this.setData({
      modal_show_2: false,
      teacher_buttonShow:false,
    })
  },

  //跳转到题库
  gotoTiku:function(){
    wx.navigateTo({
      url: '/pages/classHomePage/tiku/index/index',
    })
  },

  // 学生端用到的函数
    //学生抽取题目
    blindbox:function(){
      var _this = this
      console.log("学生抽取题目")
        let data= {
          blindBoxId: _this.data.blindBoxId,
        }
    
        app.formPost('/api/admin/blindbox/blindbox',data).then(res=>{
          console.log('学生抽题结果：',res);
          _this.setData({
            student_buttonShow: true,
            timu: JSON.parse(JSON.stringify(res['response']['titleItems'][0]).replace(/<[^>]*>/g, ''))
          })
          // if(res['response']['mention']!=null){
          //   _this.setData({
          //     mention_string: String(res['response']['mention']),
          //   })
          //   return
          // }
          res = JSON.parse(JSON.stringify(res).replace(/<[^>]*>/g, ''))
          //题目：timu['questionItems'][0]['title'] 
          // questionItems:timu['questionItems'][0]['items']
    
          _this.setData({
            //有关题目选项的数据
            "itemOrder": res['response']['titleItems'][0]['questionItems'][0]['itemOrder'],
            "exam_paper_id":res['response']['id'],
            "questionType": res['response']['titleItems'][0]['questionItems'][0]['questionType'],
            "doTime": res['response']['suggestTime'],
            "paperId": res['response']['id']
          })
          // console.log("试卷id:"+_this.data.exam_paper_id)
        })
    },
    //捕捉学生选择选项的改变事件
    answerChange(e){
      console.log(e)
      console.log("用户选择的答案是："+e.detail.value)
      let _this = this
      _this.setData({
        "studentAnswer": e.detail.value,
      })
      if(String(_this.data.studentAnswer).substr(0,1)==_this.data.timu['questionItems'][0]['correct']){
        _this.setData({
          "is_right":1
        })
      }else{
        _this.setData({
          "is_right":0,
        })
      }
    },
  
    //学生提交答案
    submitAnswer: function(){
      let _this = this
      //数据
      let data = {
        "blindBoxId":_this.data.blindBoxId,
        "is_right": _this.data.is_right,
        "stuanswer": _this.data.studentAnswer,
        "true_answer": _this.data.timu['questionItems'][0]['correct'],
      }
      console.log("学生提交答案")
      app.formPost("/api/admin/student/exampaper/answer/blindbox_answerSubmit",data).then(res=>{
        console.log(res)
        if(res.message=="提交答案成功"){
          wx.showToast({
            title: '提交成功！',
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000);
        }
      })
    },

    //学生提交后教师查看答题结果：
    studentAnswer: function(){
      console.log("教师查看学生答案")
      let _this = this
      let paper_id = null
      let data_1 = {
        courseName : app.globalData.banji_info.courseName,
        is_blindbox: 1,
        pageIndex: 1,
        pageSize: 10,
        paperType: 1,
        stuAccount: _this.data.chooseStudentName
      }
      /*
      //先拿到学生的题目id
      app.formPost("/api/admin/student/exampaper/pageList",data_1).then(res=>{
        paper_id = res['response']['list'][0]['id']
        // console.log("111##"+res['response']['list'][0]['id'])
        _this.setData({
          exam_paper_id: paper_id
        })
      }).then(res=>{
        //再拿到学生题目
        let data_2 = {
          id: paper_id
        }
        app.formPost("/api/admin/student/exampaper/select/"+paper_id,data_2).then(res=>{
          res = JSON.parse(JSON.stringify(res).replace(/<[^>]*>/g, ''))
          _this.setData({
            timu_title: res['response']['titleItems'][0]['questionItems'][0]['title']
          })
        }).then(res=>{
          //再拿到学生的答题情况：
          let data_3 = {
            exam_paper_id: paper_id,
            stu_account: _this.data.stuaccount
          }
          app.formPost("/api/admin/student/exampaper/answer/blindbox_view",data_3).then(res=>{
            _this.setData({
              stu_answer: res[0]['stu_answer'],
              true_answer: res[0]['true_answer'],
              show_studentAnswer: true,
            })
          })
        })
      })
      */
     // 先拿到学生的题目 id
      app.formPost("/api/admin/student/exampaper/pageList", data_1).then(res => {
      // 检查 res['response']['list'] 是否存在且不为空
      if (res && res.response && res.response.list && res.response.list.length > 0) {
        const paper_id = res.response.list[0].id;
        _this.setData({
          exam_paper_id: paper_id
        });

        // 再拿到学生题目
        let data_2 = {
          id: paper_id
        };
        return app.formPost("/api/admin/student/exampaper/select/" + paper_id, data_2);
      } else {
        console.error('未获取到题目列表');
        return Promise.reject('未获取到题目列表');
      }
    }).then(res => {
    // 检查 res['response']['titleItems'] 是否存在且不为空
    if (res && res.response && res.response.titleItems && res.response.titleItems.length > 0) {
      res = JSON.parse(JSON.stringify(res).replace(/<[^>]*>/g, ''));
      _this.setData({
        timu_title: res.response.titleItems[0].questionItems[0].title
      });

      // 再拿到学生的答题情况
      let data_3 = {
        exam_paper_id: _this.data.exam_paper_id,
        stu_account: _this.data.stuaccount
      };
      return app.formPost("/api/admin/student/exampaper/answer/blindbox_view", data_3);
    } else {
      console.error('未获取到题目详情');
      return Promise.reject('未获取到题目详情');
    }
  }).then(res => {
    // 检查 res[0] 是否存在
    if (res && res.length > 0) {
      _this.setData({
       stu_answer: res[0].stu_answer,
        true_answer: res[0].true_answer,
        show_studentAnswer: true,
      });
    } else {
      console.error('未获取到学生答题情况');
    }
  }).catch(err => {
    console.error('请求失败:', err);
  });
  },

    blindboxFinish: function(){

      this.setData({
        show_studentAnswer: false,
      })
      wx.showToast({
        title: '本次盲盒结束',
      })

      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 1000);
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(_this.data.timu['title'])
    let _this=this
    _this.setData({
      people: wx.getStorageSync("people"),
      code: wx.getStorageSync('myCode'),
      // teacher_account: wx.getStorageSync('account'),
    })
    if(this.data.people=="teacher"){
      _this.setData({
        teacher_account: wx.getStorageSync('account'),
      })
    }else if(this.data.people=="student"){
      _this.setData({
        stu_name: wx.getStorageSync('account'),
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    let _this = this
    if(_this.data.people=='student')
    {
      let data = {
        stuAccount: wx.getStorageSync('account'),
      }
      
      app.formPost("/api/admin/blindbox/view_result",data).then(res=>{
        if(res[0]['id']!=null){
          _this.setData({
          chooseFlag: true,
          blindBoxId: res[0]['id']
        })
      }else{
        return
      }
      })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})